package controllers;
import play.*;
import play.mvc.*;
import play.mvc.Http.Session;
import play.data.*;
import static play.data.Form.*;
import models.*;
import play.db.ebean.*;

import org.apache.commons.lang3.StringUtils;
import play.mvc.Controller;

import java.text.ParseException;
import java.util.*;

import views.html.CreateQCM.*;

public class CreateQCM extends Controller {
	
	
    
	/**
     * Navigation entre les étapes. 
     * On sauvegarde le qcm dans la session 
     */ 
	public static Result step(int step) {
	
	   	try {
	   		Qcm qcm = toQcm(session());
	   		Form<Qcm> qcmForm = form(Qcm.class).fill(qcm);
	   		if (step == 1) {
	   			return ok(initiateQcm.render(qcmForm));
	   			} else {
		   		System.out.println("step2 : "+ qcm.getCleAuthentification()+qcm.getLibelle()+qcm.getStatut()+qcm.getDateCloture()+qcm.getDateCreation()+qcm.getDateOuverture()+qcm.getListeQuestions());
		   		List<Theme> allThemes = Theme.findAll();
		   		for (Theme elem: allThemes)
		        {
		          	 System.out.println (elem.getLibelleT());
		          }	
		   		return ok(associerQuestionQcm.render(qcmForm,qcm,allThemes));
	   			}
	   		}catch(ParseException e){
	   			e.printStackTrace();
	   		}
	   	//TODO : renvoyer un message d'erreur
	   	return forbidden();
	}
	  
	
	/**
     * Creation d'un objet qcm avec les donnees de la session 
     */
	private static Qcm toQcm(Session session) throws ParseException {
		Qcm qcm = new Qcm();
		GregorianCalendar g=new GregorianCalendar();
	    List<Question> listeQuestions=new ArrayList<Question>();
		qcm.setCleAuthentification("toto");
		qcm.setDateCreation(g.getTime());
		if(session.get("dateCloture")!=null){
			qcm.setDateCloture(Utile.stringToDate(session.get("dateCloture")));
		}
		if(session.get("dateOuverture")!=null){
		qcm.setDateOuverture(Utile.stringToDate(session.get("dateOuverture")));
		}
		qcm.setLibelle(session.get("libelle"));
		qcm.setListeQuestions(listeQuestions);
		User e = User.findById(1L);
		qcm.setUser(e);
		
		return qcm;
	}	
	
	private static Map<String, String> toMap(Form<?> qcm) {
		 // Fill the form with data session
		Map<String, String> map = new HashMap<String, String>();
		map.put("libelle", qcm.field("libelle").valueOr(""));
		map.put("dateOuverture", qcm.field("dateOuverture").valueOr(""));
		map.put("dateCloture", qcm.field("dateCloture").valueOr(""));
		map.put("theme", qcm.field("theme").valueOr(""));
		map.put("matiere", qcm.field("matiere").valueOr(""));
		map.put("chapitre", qcm.field("chapitre").valueOr(""));
		map.put("listeQuestions", qcm.field("listeQuestions").valueOr(""));
		return map ;
	}
	

	/**
     * Envoie de chaque partie de la creation du QCM 
     */
	public static Result submit(int step) {
	  	
		if (step == 1) {
			return handleStep1Submission();
		} else {
			return handleStep2Submission();
		}
    }
	
	 private static Result handleStep1Submission() {
		 	//TODO filledForm nous servira à vérifier que les données sont bon
			DynamicForm filledForm = form().bindFromRequest();
			session().putAll(toMap(filledForm));
			System.out.println("formeStep1 : "+ filledForm.toString());
			System.out.println("sessionStep1: "+session().toString());
		 	return redirect(routes.CreateQCM.step(2));
		}
		
		private static Result handleStep2Submission() {
			DynamicForm filledForm = form().bindFromRequest();
			System.out.println("formeStep2 : "+ filledForm.toString());
			System.out.println("sessionStep2 : "+session().toString());
			if ("retour".equals(filledForm.field("action").value())) {
	            return redirect(routes.CreateQCM.step(1));
			} else {
				session().putAll(toMap(filledForm));
				System.out.println("sessionStep2apresput : "+session().toString());
				Qcm created = new Qcm();
				created=buildResponse(filledForm);				
				created.save();
				//Clear the session
				session().clear();
			    return ok(recupilatif.render(created));
			}	
	    }


		private static Qcm buildResponse(DynamicForm filledForm){
			Qcm created=new Qcm();
			created.setIdQcm(7L);
			created.setCleAuthentification("toto");
			try {
				created.setDateCloture(Utile.stringToDate(filledForm.get("dateCloture")));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			GregorianCalendar g = new GregorianCalendar();
			created.setDateCreation(g.getTime());
			try {
				created.setDateOuverture(Utile.stringToDate(filledForm.get("dateOuverture")));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//TODO faire un test pour vérifier que le user dispose bien des droits ?? 
			User e = User.findById(1L);
			created.setUser(e);
			created.setLibelle(filledForm.get("libelle"));
			created.setListeQuestions(null);
			return created;		
		}
		
		private static List<Matiere> getMatieresbyTheme(Long id){
			Theme t= Theme.findById(id);
			List<Matiere> AllMatieres = t.getSesMatieres();			
			return AllMatieres;
		}
}